package com.trinity.sample.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Handler
import android.os.Message
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.trinity.sample.R

/**
 *  自定义录像按钮
 */
class RecordButton : View {

  private var paint: Paint? = null
  private var mOnGestureListener: OnGestureListener? = null
  /**绘圆的半径*/
  private var currentRadius: Float = 0.toFloat()
  private var isDown: Boolean = false

  constructor(context: Context) : super(context) {
    init()
  }

  constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
    init()
  }

  constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
    init()
  }

  private fun init() {
    paint = Paint()
    paint?.isAntiAlias = true
    paint?.style = Paint.Style.FILL
  }



  override fun onTouchEvent(event: MotionEvent): Boolean {

    when (event.action) {
      MotionEvent.ACTION_DOWN -> {
        val parent = parent as ViewGroup
        parent.requestDisallowInterceptTouchEvent(true) //设置它的父控件 不要拦截我的事件

        isDown = true
        mOnGestureListener?.onDown()
        postInvalidate()
      }

      MotionEvent.ACTION_UP -> {
        val parent1 = parent as ViewGroup
        parent1.requestDisallowInterceptTouchEvent(false)
        isDown = false
        mOnGestureListener?.onUp()
        postInvalidate()
      }
    }
    return true
  }



  override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)

    if(currentRadius.toInt()==0){
      currentRadius = width/2f ;
    }

    if (isDown) {
      paint?.color = Color.parseColor("#1cd76c")
    } else {
      paint?.color = Color.WHITE
    }

    paint?.let {
      canvas.drawCircle(width / 2f, height / 2f, currentRadius, it)
    }
  }

  fun setOnGestureListener(listener: OnGestureListener) {
    this.mOnGestureListener = listener
  }

  interface OnGestureListener {
    fun onDown()
    fun onUp()
  }
}
